package org.jeecg.modules.demo.temple.order.controller;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.FileDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;

import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.WeChatQrCodeUtils;
import org.jeecg.modules.demo.temple.donation.entity.TempleDonation;
import org.jeecg.modules.demo.temple.donation.service.ITempleDonationService;
import org.jeecg.modules.demo.temple.order.entity.TempleDonationOrder;
import org.jeecg.modules.demo.temple.order.service.ITempleDonationOrderService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.demo.temple.pay.entity.TempleMerchantInfo;
import org.jeecg.modules.demo.temple.pay.service.IJxyhPayService;
import org.jeecg.modules.demo.temple.pay.service.ITempleMerchantInfoService;
import org.jeecg.modules.demo.temple.sys.service.ISysDepart;
import org.jeecg.modules.demo.temple.sys.entity.SysDepart;
import org.jeecg.modules.demo.temple.weixin.entity.TempleUser;
import org.jeecg.modules.demo.temple.weixin.service.ITempleUserService;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 供养订单表
 * @Author: jeecg-boot
 * @Date: 2022-05-04
 * @Version: V1.0
 */
@Api(tags = "供养订单表")
@RestController
@RequestMapping("/temple.order/templeDonationOrder")
@Slf4j
public class TempleDonationOrderController extends JeecgController<TempleDonationOrder, ITempleDonationOrderService> {
    @Autowired
    private ITempleDonationOrderService templeDonationOrderService;

    @Autowired
    private ITempleUserService templeUserService;

    @Autowired
    private ITempleDonationService templeDonationService;

    @Autowired
    private ISysDepart sysDepartService;
    // 生成二维码工具

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Autowired
    private WeChatQrCodeUtils weChatQrCodeUtils;  //= new WeChatQrCodeUtils() ;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ITempleMerchantInfoService templeMerchantInfoService;

    @Autowired
    private IJxyhPayService jxyhPayService;


    @Value(value = "${justauth.type.WECHAT_QRCODE.appId}")
    private String  appId  ;
    @Value(value = "${justauth.type.WECHAT_QRCODE.appSecret}")
    private String  appSecret  ;
    @Value(value = "${justauth.type.WECHAT_QRCODE.accessToken_URL}")
   private String  accessToken_URL ;
    @Value(value = "${justauth.type.WECHAT_QRCODE.request_URL}")
    private String  request_URL ;



    /**
     * 分页列表查询
     *
     * @param templeDonationOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "供养订单表-分页列表查询")
    @ApiOperation(value = "供养订单表-分页列表查询", notes = "供养订单表-分页列表查询")
    @GetMapping({"/list", "/api/list"})
    public Result<IPage<TempleDonationOrder>> queryPageList(TempleDonationOrder templeDonationOrder,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize,
                                                            HttpServletRequest req) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 判断用户类型
        if (loginUser != null) {
            templeDonationOrder.setSysOrgCode(loginUser.getOrgCode());
        }
        QueryWrapper<TempleDonationOrder> queryWrapper = QueryGenerator.initQueryWrapper(templeDonationOrder, req.getParameterMap());
        // 设置查询条件
        queryWrapper.orderByDesc("create_time");
        queryWrapper.eq("is_pay","Y");
        //queryWrapper.like("module_name",templeDonationOrder.getModuleName()) ;

        Page<TempleDonationOrder> page = new Page<TempleDonationOrder>(pageNo, pageSize);
        IPage<TempleDonationOrder> pageList = templeDonationOrderService.page(page, queryWrapper);
        for (TempleDonationOrder o : pageList.getRecords()) {
            TempleUser user = new TempleUser();
            user.setId(o.getUserId());
            QueryWrapper<TempleUser> wrapper = QueryGenerator.initQueryWrapper(user, req.getParameterMap());
            user = templeUserService.getOne(wrapper);
            o.setUser(user);
        }
        return Result.OK(pageList);
    }

    @ApiOperation(value = "供养订单表-订单总数", notes = "供养订单表-订单总数")
    @GetMapping({"/api/count"})
    public Result<Integer> queryCount(TempleDonationOrder templeDonationOrder,
                                      HttpServletRequest req) {
        templeDonationOrder.setIsPay("Y");
        QueryWrapper<TempleDonationOrder> queryWrapper = QueryGenerator.initQueryWrapper(templeDonationOrder, req.getParameterMap());
        Integer cnt = templeDonationOrderService.count(queryWrapper);
        return Result.OK(cnt);
    }

    /**
     * 添加
     *
     * @param templeDonationOrder
     * @return
     */
    @AutoLog(value = "供养订单表-添加")
    @ApiOperation(value = "供养订单表-添加", notes = "供养订单表-添加")
    @PostMapping({"/add", "/api/add"})
    //@PostMapping("/api/add")

    public Result<Map<String,String>> add(@RequestBody TempleDonationOrder templeDonationOrder,HttpServletRequest req) {

        log.info(templeDonationOrder.getDonationId()) ;
        ClassPathResource classPathResource = new ClassPathResource("/image/donationCert.jpg");
        InputStream inputStream = null;
        Map orderMap = new HashMap<String,String>();
        try {
            // 保存订单数据
            templeDonationOrderService.save(templeDonationOrder);
            TempleMerchantInfo templeMerchantInfo = new TempleMerchantInfo();
            templeMerchantInfo.setSysOrgCode(templeDonationOrder.getSysOrgCode());
            QueryWrapper<TempleMerchantInfo> queryWrapper = QueryGenerator.initQueryWrapper(templeMerchantInfo, req.getParameterMap());
            templeMerchantInfo = templeMerchantInfoService.getOne(queryWrapper);
            String merchantNo = templeMerchantInfo.getMerchantNo();
            String privateKey = templeMerchantInfo.getPrivateKey();
            String publicKey = templeMerchantInfo.getPublicKey();
            String apiKey = templeMerchantInfo.getApiKey();
            String userId = templeDonationOrder.getUserId();
            String sysOrgCode = templeDonationOrder.getSysOrgCode();
            TempleUser user = templeUserService.getById(userId);
            SysDepart depart = new SysDepart();
            depart.setOrgCode(sysOrgCode);
            QueryWrapper<SysDepart> queryWrapper2 = QueryGenerator.initQueryWrapper(depart, req.getParameterMap());
            SysDepart sysDepart = sysDepartService.getOne(queryWrapper2);
            String appId=sysDepart.getWechatMiniAppId();
            String openId = user.getOpenId();
            String transAmt = templeDonationOrder.getAmount().multiply(new BigDecimal("100")).toString();//元转分
//            String transAmt = "1";//调试支付1分钱
            Map<String,String> map = jxyhPayService.payWechatOrder(transAmt,
                                                                templeDonationOrder.getModuleName(),
                                                                templeDonationOrder.getModuleName(),
                                                                "D"+templeDonationOrder.getId(),
                                                                merchantNo,
                                                                "https://godhouse.jxlwtech.com/jeecg-boot/temple.pay/jxyhPayContoller/api/notify",
                                                                "www.baidu.com",
                                                                privateKey,
                                                                publicKey,
                                                                apiKey,
                                                                appId,
                                                                openId);



            inputStream = classPathResource.getInputStream();
            BufferedImage image = ImageIO.read(inputStream);
            int width = image.getWidth();
            int height = image.getHeight();

            // 创建画笔(image为上一步的图片对象)
            Graphics2D pen = image.createGraphics();
            // 设置画笔颜色为白色
            pen.setColor(Color.black);
            // 设置画笔字体样式为微软雅黑，斜体，文字大小为20px
            pen.setFont(new Font("宋体", Font.BOLD, 72));
            pen.drawString("捐赠证书", 400, 250);
            //尊敬的
            pen.setFont(new Font("楷体", Font.PLAIN, 48));
            pen.drawString("尊敬的", 140, 400);

            String str1 = "感谢您使用线上捐赠系统！您为";
            pen.drawString(str1, 230, 500);
            String str2 = "捐赠项目：";
            pen.drawString(str2, 140, 600);
            //项目名称
            String str3 = "成功捐助" + templeDonationOrder.getAmount() + "元，捐赠单号：";
            pen.drawString(str3, 140, 700);
            pen.drawString("D"+templeDonationOrder.getId(), 140, 800);
            String str4 = "对您的支持表示诚挚的敬意，特此";
            pen.drawString(str4, 230, 900);
            String str5 = "证明！";
            pen.drawString(str5, 140, 1000);

            pen.setFont(new Font("楷体", Font.BOLD, 48));
            pen.drawString(StringUtils.isEmpty(templeDonationOrder.getName())?"匿名":templeDonationOrder.getName(), 350, 400);

            // 依据捐赠id获取捐赠项目


            TempleDonation templeDonationServiceById = templeDonationService.getById(templeDonationOrder.getDonationId());

            pen.drawString(templeDonationServiceById.getName(), 400, 600);

            DateFormatter d = new DateFormatter("YYYY-MM-dd");
            String str6 = d.print(templeDonationOrder.getCreateTime(), Locale.CHINA);
            pen.drawString(str6, 680, 1200);
            pen.setFont(new Font("楷体", Font.BOLD, 56));
            String str7 = "证明！";

            // 把二维码写到捐赠模板上

            String acccesToken =  weChatQrCodeUtils.getAccessToken(accessToken_URL,appId,appSecret,redisUtil) ;
//            String page = "pages/donation/detail";//小程序转跳地址
            String page = "";
            String scene = "id="+templeDonationOrder.getDonationId();//场景参数
            InputStream QrCode = weChatQrCodeUtils.generateQrCode(acccesToken, request_URL, page, scene);


//            FileInputStream imageInputStream =  new FileInputStream(upLoadPath+File.separator+QrCode) ;

            BufferedImage QrcodeImage = ImageIO.read(QrCode) ;
            // pen.drawImage(QrcodeImage.getScaledInstance(width / 4, width / 4, Image.SCALE_DEFAULT), width - (width / 4)-10, height - (width / 4)- 10, null);
            if(QrcodeImage!= null) {
                pen.drawImage(QrcodeImage.getScaledInstance(width / 5, width / 5, Image.SCALE_DEFAULT), 140, 1100, null);
            }
            // 获取对应的所属部门
            LambdaQueryWrapper<SysDepart> sysDepartLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sysDepartLambdaQueryWrapper.eq(templeDonationOrder.getSysOrgCode()!= null,SysDepart::getOrgCode,templeDonationOrder.getSysOrgCode()) ;
            SysDepart sysDepartServiceOne = sysDepartService.getOne(sysDepartLambdaQueryWrapper);
            String name = sysDepartServiceOne.getDepartName() ;
            int len = 24 - name.length();
            String format = String.format("%" + len + "s", name);
            pen.drawString(format, 225, 1100);

            pen.setFont(new Font("楷体",Font.BOLD,36));
            String str8 = "扫一扫，再次捐赠";
            pen.drawString(str8,140,1350);

            ByteArrayOutputStream bs =new ByteArrayOutputStream();
            ImageIO.write(image, "jpg", bs);

            FileDTO fd = new FileDTO("voucher.jpg",bs.toByteArray());

            String payVoucher = CommonUtils.upload(fd,"temp",uploadpath);
            templeDonationOrder.setPayVoucher(payVoucher);
            templeDonationOrderService.updateById(templeDonationOrder);
            bs.close();

            orderMap = JSON.parseObject(JSON.toJSONString(templeDonationOrder),new TypeReference<Map<String, String>>() {});
            orderMap.putAll(map);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("支付失败");
        }



        return Result.OK(orderMap);
    }

    /**
     * 编辑
     *
     * @param templeDonationOrder
     * @return
     */
    @AutoLog(value = "供养订单表-编辑")
    @ApiOperation(value = "供养订单表-编辑", notes = "供养订单表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody TempleDonationOrder templeDonationOrder) {
        templeDonationOrderService.updateById(templeDonationOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "供养订单表-通过id删除")
    @ApiOperation(value = "供养订单表-通过id删除", notes = "供养订单表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        templeDonationOrderService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "供养订单表-批量删除")
    @ApiOperation(value = "供养订单表-批量删除", notes = "供养订单表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.templeDonationOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "供养订单表-通过id查询")
    @ApiOperation(value = "供养订单表-通过id查询", notes = "供养订单表-通过id查询")
    @GetMapping({"/queryById","/api/queryById"})
    public Result<TempleDonationOrder> queryById(@RequestParam(name = "id", required = true) String id) {
        TempleDonationOrder templeDonationOrder = templeDonationOrderService.getById(id);
        if (templeDonationOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(templeDonationOrder);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param templeDonationOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, TempleDonationOrder templeDonationOrder) {
        return super.exportXls(request, templeDonationOrder, TempleDonationOrder.class, "供养订单表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, TempleDonationOrder.class);
    }

}
